package org.ssi.web.result;

import java.io.OutputStream;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * 功能概述：<br>
 * 基于实现XMLNode结点的序列化
 * 
 * @author 王国东
 */
public class XMLNodeWriter {
	/**   */
	private XMLNode rootNode;

	/** 文档对象 */
	private Document document = null;

	/**
	 * @param rootNode
	 */
	public XMLNodeWriter(XMLNode rootNode) {
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder builder;
		try {
			builder = builderFactory.newDocumentBuilder();
			this.document = builder.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		this.rootNode = rootNode;
	}

	/**
	 * @param charset
	 * @param out
	 */
	public void writeXmlContent(Charset charset, OutputStream out) {
		Node root = rootNode.toXMLNode(document);
		this.document.appendChild(root);
		AbstXmlBuilder.domToStream(this.document, charset, out);
	}

	/**
	 * @param charset
	 * @return
	 */
	public final String getXmlContent(Charset charset) {
		Node root = rootNode.toXMLNode(document);
		this.document.appendChild(root);
		String xmlContent = AbstXmlBuilder.domToString(this.document, charset);
		return xmlContent;
	}

}
